<!--
 描述: 主页模板
 作者: Jack Chen
 日期: 2020-06-15
-->

<template>
    <div class="home-container">
        <Header />
  
      <div class="content clearfix">
        <div class="list">
          <Form :model="formFind" ref="formFind" style="flex-wrap: wrap;" v-if="normalUserID==0">
            <Col span="4">
                <FormItem label="手机号：" prop="username" label-position="left" :label-width=70>
                    <Input v-model="formFind.username" placeholder="请输入手机号" />
                </FormItem>
            </Col>
            <Col span="6">
                <FormItem label="注册时间：" prop="gmt_create" label-position="left" :label-width=90>
                  <DatePicker :editable="false" v-model="formFind.gmt_create" type="daterange" placeholder="请选择日期范围"></DatePicker>
                </FormItem>
            </Col>
            <Col span="3">
                <FormItem label="呢称：" prop="nickname" label-position="left" :label-width=60>
                    <Input v-model="formFind.nickname" placeholder="请输入呢称" />
                </FormItem>
            </Col>
            <Col span="4">
                <FormItem label="状态：" prop="status" label-position="left" :label-width=100>
                    <Select v-model="formFind.status" placeholder="请选择状态" >
                        <Option v-for="(item,index) in USER_STATUS" :key="index" :value="item.value">{{ item.name }}</Option>
                    </Select>
                </FormItem>
            </Col>
            <Col span="4">
                <FormItem label="权限：" prop="user_type" label-position="left" :label-width=100>
                    <Select v-model="formFind.user_type" placeholder="请选择权限" >
                        <Option v-for="(item,index) in USER_TYPE" :key="index" :value="item.value">{{ item.name }}</Option>
                    </Select>
                </FormItem>
            </Col>
            <Col span="4">
                <FormItem label="所属老师：" prop="master_id" label-position="left" :label-width=100>
                    <Select v-model="formFind.master_id" placeholder="请选择所属老师" >
                        <Option v-for="(item,index) in allMasters" :key="index" :value="item.value">{{ item.name }}</Option>
                    </Select>
                </FormItem>
            </Col>
            <Col span="3" style="text-align:center">
                <Button type="primary" icon="md-search" size="large" @click="getTaskList">查找用户</Button>
            </Col>
            <Col span="2" style="text-align:center">
                <Button type="info" icon="md-trash" size="large" @click="handleReset('formFind')">重置</Button>
            </Col>
            <Col span="2" style="text-align:center">
                <Button type="success" icon="md-add" size="large" @click="addTask">添加用户</Button>
            </Col>
          </Form>
            
        </div>
  
        <Table style='min-height: 60vmin;' :loading="loading" :columns="columns" :data="tableData">
          <template slot-scope="{ row, index }" slot="action">
           
            <Button type="primary" ghost style="margin-right: 10px" @click="edit(index)">编辑</Button>
            <Button type="error" ghost @click="remove(row.id)">删除</Button>
          </template>
        </Table>
  
        <Page
          class-name="pagination"
          show-total
          show-sizer
          :total="total"
          @on-page-size-change="handlePageSizeChange"
          @on-change="handleCurrentChange"
          :page-size="pageSize"
          :page-size-opts="pageSizeOpts"
          :current="pageNo"
          v-if="!loading && total > 0"
        />
      </div>
  
      <Footer />
  
      <Drawer
        :title="title"
        v-model="isShow"
        width="600"
        :styles="styles"
        :mask-closable="true"
      >
        <Form :model="formValidate" ref="formValidate" :rules="ruleValidate">
            <Col span="15">
                <FormItem label="手机号：" prop="username" label-position="left" :label-width=80>
                    <Input v-model="formValidate.username" placeholder="请输入手机号" :disabled="type<=0"/>
                </FormItem>
            </Col>
            <Col span="15">
                <FormItem label="密码：" prop="password" label-position="left" :label-width=80>
                    <Input type="password" v-model="formValidate.password" placeholder="请输入密码" :disabled="type<=0"/>
                </FormItem>
            </Col>
            <Col span="16">
                <FormItem label="注册时间：" prop="gmt_create" label-position="left" :label-width=90>
                  <DatePicker :editable="false" v-model="formValidate.gmt_create" type="datetime" placeholder="请选择创建时间" :disabled="type<=0"></DatePicker>
                </FormItem>
            </Col>
            <Col span="14">
                <FormItem label="姓名：" prop="nickname" label-position="left" :label-width=60>
                    <Input v-model="formValidate.nickname" placeholder="请输入姓名"  :disabled="type<=0"/>
                </FormItem>
            </Col>
            <Col span="14">
                <FormItem label="状态：" prop="status" label-position="left" :label-width=60>
                    <Select v-model="formValidate.status" placeholder="请选择状态"  :disabled="type<=0">
                        <Option v-for="(item,index) in USER_STATUS" :key="index" :value="item.value" v-if="item.value>=0">{{ item.name }}</Option>
                    </Select>
                </FormItem>
            </Col>
            <Col span="14">
                <FormItem label="权限：" prop="user_type" label-position="left" :label-width=60>
                    <Select v-model="formValidate.user_type" placeholder="请选择权限"  :disabled="type<=0">
                        <Option v-for="(item,index) in USER_TYPE" :key="index" :value="item.value" v-if="item.value>=0">{{ item.name }}</Option>
                    </Select>
                </FormItem>
            </Col>
            <Col span="14">
                <FormItem label="所属老师：" prop="master_id" label-position="left" :label-width=90>
                    <Select v-model="formValidate.master_id" placeholder="请选择所属老师"  :disabled="type<=0">
                        <Option v-for="(item,index) in allMasters" :key="index" :value="item.value" v-if="item.value>=0">{{ item.name }}</Option>
                    </Select>
                </FormItem>
            </Col>
            <Col span="24">
                <FormItem label="词汇包：" prop="bookIds" label-position="left" :label-width=80>
                  <CheckboxGroup v-model="formValidate.bookIds" >
                    <Checkbox v-for="(item,index) in allBooks" :key="item.id" :label="item.id" >{{ item.name }}</Checkbox>
                  </CheckboxGroup>
                </FormItem>
            </Col>
        </Form>
        <div class="demo-drawer-footer">
          <Button type="primary" style="margin-right: 15px" @click="handleSubmit('formValidate')" v-if="type>0">{{ textBtn }}</Button>
           <Button @click="handleReset('formValidate')" style="margin-right: 15px" v-if="type>0">重置</Button>
          <Button type="error" ghost @click="isShow = false" v-if="type>0">取消</Button>
        </div>
      </Drawer>    
  
  
    </div>
  </template>
  
  <script>
  import Header from '@/components/Header';  
  import Footer from '@/components/Footer'; 
  import store from '../store'
  import { 
    int2SingleString,
  } from '@/utils/global';
  import { 
    formatTime,
    formatDate
  } from '@/utils/valid';
  import { 
    getUserList,
    editUser,
    addUser,
    deleteUser,
    getUserBookIds,
    getBookList
  } from '@/utils/api';
  
  export default {
    name: 'User',
    components: {
      Header,
      Footer
    },
    data() {
        return {
          normalUserID: 0,
          loading: true,
          total: 0,
          pageNo: 1,
          pageSize: 50,
          pageSizeOpts: [10,50,100,200],
          textBtn: '提交',
          type: 1, // 1:添加 2:编辑
          title: '添加用户',
          isShow: false,
          styles: {
            height: 'calc(100% - 120px)',
            overflow: 'auto',
            position: 'static'
          },
          formFind: {
            username: '',
            gmt_create: [],
            nickname: '',
            status: -1,
            user_type: -1,
            master_id: -1
          },
          formValidate: {
            id: 0,
            username: '',
            password: '',
            gmt_create: formatTime(new Date()),
            nickname: '',
            bookIds: [],
            status: 0,
            user_type: 0,
            master_id: 0
          },
          USER_STATUS : [
            {name:'全部',value:-1},
            {name:'可用',value:0},
            {name:'禁用',value:1}
          ],
          USER_TYPE : [
            {name:'全部',value:-1},
            {name:'学生',value:0},
            {name:'管理员',value:1},
            {name:'老师',value:2},
            {name:'优秀学员',value:3}
          ],
          columns: [
            {
              title: 'ID',
              key: 'id',
              width: 80,
              align: 'center'
            },
            {
              title: '手机号',
              key: 'username',
              width: 160,
              align: 'center'
            },
            {
              title: '姓名',
              key: 'nickname',
              width: 240,
              align: 'center'
            },
            {
              title: '年龄',
              key: 'age',
              width: 80,
              align: 'center'
            },
            {
              title: '性别',
              key: 'sex',
              width: 80,
              align: 'center'
            },
            {
              title: '状态',
              key: 'status',
              width: 120,
              render: (h,params) => {
                  const row = params.row;
                  return h('div', int2SingleString( row.status, this.USER_STATUS));
              }
            },
            {
              title: '权限',
              key: 'user_type',
              width: 120,
              render: (h,params) => {
                  const row = params.row;
                  return h('div', int2SingleString( row.user_type, this.USER_TYPE));
              }
            },
            {
              title: '所属老师',
              key: 'master_id',
              width: 160,
              render: (h,params) => {
                  const row = params.row;
                  return h('div', int2SingleString( row.master_id, this.allMasters));
              }
            },
            {
              title: '注册时间',
              key: 'gmt_create',
              render: (h, params) => {
                const row = params.row;
                const text = formatTime(row.gmt_create);
                return h('div', text);
              }
            },
            {
              title: '操作',
              width: 220,
              slot: 'action',
              align: 'center'
            }
          ],
          tableData: [],
          ruleValidate: {
            username: [
              { required: true, message: '手机号不能为空', trigger: 'blur' }
            ],
          },
          allBooks: [],
          allMasters: [],
        }
    },
    computed: {
        
    },
    created() {},
    mounted() {
      this.normalUserID = 0;
      let user_type = store.state.userInfo.data.userData.user_type;
      if(user_type != 1){
        this.normalUserID = store.state.userInfo.data.userData.id;
      }
      this.getAllBookList();
      this.getAllMasterList();
      setTimeout(() => {
        this.getTaskList();
      }, 1000);
    },
    methods: {
      // 页码改变的回调，返回改变后的页码
      handleCurrentChange(val) {
        console.log(val)
        this.pageNo = val;
        this.getTaskList();  
      },
      handlePageSizeChange(val) {
        console.log(val)
        this.pageSize = val;
        this.getTaskList();  
      },
      // 获取任务列表数据
      getTaskList() {
        this.loading = true;
  
        let data = {
          id: this.normalUserID,
          username: this.formFind.username,
          gmt_create: [formatDate(this.formFind.gmt_create[0]), formatDate(this.formFind.gmt_create[1])],
          nickname: this.formFind.nickname,
          status: this.formFind.status,
          user_type: this.formFind.user_type,
          master_id: this.formFind.master_id
        }
        console.log( data)
        let params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          params: data
        }
  
        getUserList(params)
        .then(res => {
          console.log('用户列表===', res);
          this.loading = false;
          if (res.code == 0 && res.data) {
            this.tableData = res.data.rows;
            this.total = res.data.total;
          } else {
            this.tableData = [];
            this.total = 0;
          }
        })
        .catch(() => {
          this.loading = false;
        })
      },
      getAllBookList() {
        let params = {
          pageSize: 999,
          params: {}
        }
  
        console.log( 'getAllBookList', params)
        getBookList(params)
        .then(res => {
          console.log('词汇包列表===', res);
          this.allBooks = [];
          if (res.code == 0 && res.data) {
            this.allBooks = res.data.rows;
            this.allBooks.sort((a,b)=> a.name.localeCompare(b.name));
          }
        })
        .catch(() => {
          this.allBooks = [];
        })
      },
      getAllMasterList() {
        let params = {
          pageSize: 999,
          params: {user_type: 2}
        }
  
        console.log( 'getAllMasterList', params)
        this.allMasters = [{name:'全部', value:-1}, {name:'未绑定', value:0}];
        getUserList(params)
        .then(res => {
          console.log('老师列表===', res);
          if (res.code == 0 && res.data) {
            for( let item of res.data.rows){
              this.allMasters.push({name:item.nickname, value: item.id})
            }
          }
        })
        .catch(() => {
        })
      },
      getBookIds(user_id) {
        let params = {
          user_id
        }
  
        getUserBookIds(params)
        .then(res => {
          console.log('用户词汇包===', res);
          this.formValidate.bookIds = [];
          if (res.code == 0 && res.data) {
            for( let i of res.data.rows){
              this.formValidate.bookIds.push(i.book_id)
            }
          }
        })
        .catch(() => {
          this.formValidate.bookIds = [];
        })
      },
      // 添加任务
      addTask() {
        this.isShow = true;
        this.textBtn = '提交';
        this.title = '添加用户';
        this.type = 1;
        this.$refs['formValidate'].resetFields();
      },
      // 编辑任务
      edit(index) {
        this.complete(index)

        this.textBtn = '保存';
        this.title = '编辑用户';
        this.type = 2;
      },
      // 详情
      complete(index) {
        this.isShow = true;
        this.title = '用户详情';
        this.type = 0;
        if( index < this.tableData.length){
          let row = this.tableData[index];
          this.formValidate = {
            id: row.id,
            username: row.username,
            gmt_create: formatTime(row.gmt_create),
            nickname: row.nickname,
            cardno: row.cardno,
            balance: row.balance,
            status: row.status,
            bookIds: [],
            user_type: row.user_type,
            master_id: row.master_id
          }
          this.getBookIds(row.id)
        }
      },
      // 删除任务
      innerRemove() {
        let data = {
          id: this.deleteId
        }
  
        deleteUser(data)
        .then(res => {
          console.log('删除用户===', res);
          if (res.code == 0) {
            this.pageNo = 1;
            this.getTaskList();
            this.$Message.success('用户删除成功');
          } else {
            this.$Message.error(res.msg);
          }
        })
      },
      // 删除任务
      remove(id) {
        let a = this;
        this.deleteId = id;
        this.$Modal.confirm({
          title: '确认删除这条数据吗？',
          onOk: function(){
            a.innerRemove()
          }
        })
      },
      // 提交添加或编辑
      handleSubmit(name) {
        console.log('handleSubmit', this.formValidate.bookIds)
        this.$refs[name].validate((valid) => {
          if (valid) {
  
            let data = {
              username: this.formValidate.username,
              password: this.formValidate.password,
              gmt_create: formatTime(this.formValidate.gmt_create),
              nickname: this.formValidate.nickname,
              status: this.formValidate.status,
              bookIds: this.formValidate.bookIds,
              user_type: this.formValidate.user_type,
              master_id: this.formValidate.master_id
            }
            if (this.type == 2) {
              data.id = this.formValidate.id;
  
              editUser(data)
              .then(res => {
                console.log('编辑用户===', res)
                this.isShow = false;
                if (res.code == 0) {
                  this.pageNo = 1;
                  this.getTaskList();
                  this.$Message.success(`${this.title}成功`);
                } else {
                  this.$Message.error(res.msg);
                }
              })
              .catch(() => {
                this.isShow = false;
              })
            }else if (this.type == 1) {
              addUser(data)
              .then(res => {
                console.log('添加用户===', res)
                this.isShow = false;
                if (res.code == 0) {
                  this.pageNo = 1;
                  this.getTaskList();
                  this.$Message.success(`${this.title}成功`);
                } else {
                  this.$Message.error(res.msg);
                }
              })
              .catch(() => {
                this.isShow = false;
              })
            }
  
          } else {
            return false;
          }
        })
      },
      // 重置表单
      handleReset (name) {
        this.$refs[name].resetFields();
      },
    }
        
  }
  </script>
  
  <style lang="scss" scoped>
  .home-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .content {
      .list {
        display: flex;
        justify-content: space-between;
        align-content: center;
        Form {
          display: flex;
        }
      }
    }
  
  }	
  </style>
  <style lang="scss">
  .ivu-table-tip table td {
    width: 100% !important;
  }
  /*.ivu-input-icon-validate {
    display: none !important;
  }*/
  .pagination {
    float: right;
    margin: 20px 0;
  }
  
  .demo-drawer-footer{
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 16px;
    background: #fff;
    display: flex;
    justify-content: space-around;
  }
  </style>